/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package slt.Controller;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import slt.Model.User;


public class ControllerServlet extends HttpServlet {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;
    
    protected String action = null;
    protected ResourceBundle rb;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.request = request;
        this.response = response;
        this.session = request.getSession(false); //Gets an old session
        
        response.addHeader("Pragma", "no-cache"); //HTTP 1.0
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); //HTTP 1.1
        response.addHeader("Cache-Control", "pre-check=0, post-check=0"); //IE
        response.setDateHeader("Expires", 0); //prevents caching at the proxy server
        
        setAction(request.getRequestURI());
        initDashboard();
        
        
        try {
            Method method = this.getClass().getMethod(action);
            method.invoke(this);
        } catch (NoSuchMethodException e) {
            response.setStatus(404);
            render("404");
        } catch (InvocationTargetException e) {
            System.err.println("From ControllerServlet: " + e.getCause());
        } catch (Exception e) {
            System.err.println("Exception: " + e);
        }
    }
    
    private void initDashboard() {
        
    }
    
    protected String getAction() {
        return action;
    }
    
    private void setAction(String uri) {
        action = uri.substring(uri.lastIndexOf("/") + 1);
        
        if(action.isEmpty()) action = "admin";
    }
    
    protected final void set(String name, Object data) {
        request.setAttribute(name, data);
    }
    
    protected final boolean getLoggedIn() {
        User user = (User)session.getAttribute("sessionUser");
        return (user != null && user.getUserId() >= 0);
    }
    
    protected final User getSessionUser() {
        return (User)session.getAttribute("sessionUser");
    }
    
    protected final void render(String address) {
        address = "/" + address + ".jsp";
        System.out.println(address);
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        
        try {
            dispatcher.forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
        protected final void redirect(String address) {
        try {
            response.sendRedirect(response.encodeRedirectURL(address));
        } catch (IOException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
   
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
